<template>
	<view class="cart-page">

		<!-- 商品列表 -->
		<view class="cart-list">
			<view v-for="(item, index) in cartList" :key="index" class="cu-item flex align-center"
				style="position: relative;">
				<!-- 店铺信息（左） -->
				<!-- <view class="shop-info" slot="left">
					<text class="shop-name">{{ item.shopName }}</text>
					<text class="arrow">></text>
				</view> -->
				<!-- 复选框（右） -->
				<checkbox-group slot="right" @change="onItemCheckChange(item,index)">
					<checkbox :value="item.id" :checked="item.check"></checkbox>
				</checkbox-group>
				<!-- 商品内容（中） -->
				<view class="goods-content">
					<image class="goods-img" :src="item.image" mode="aspectFill"></image>
					<view class="goods-info-wrap">
						<!-- 商品标题 -->
						<text class="goods-title">{{ item.title }}</text>
						<view class="goods-spec">
							<cu-tag v-for="(tag, tagIdx) in item.skuAttr" style="margin-right: 10rpx;" :key="tagIdx">
								{{ tag }}
							</cu-tag>
						</view>


						<ColorUICounter :max="999" v-model="item.count" />


						<!-- 价格区域 -->
						<view class="price-section">
							<view class="current-price">券后¥{{ item.price }}</view>
							<view class="discount">合计¥{{ item.totalPrice }}</view>
							<!-- <text class="detail">明细</text> -->
						</view>
						<!-- 优惠券说明 -->
						<!-- <text class="coupon-desc">{{ item.couponInfo }}</text> -->
					</view>

				</view>
				<!-- <view style="position: absolute;right: 15rpx;top: 10rpx;height: 30rpx;text-align: center;">
					x{{item.count}}
				</view> -->
				<view
					style="position: absolute;right: 30rpx;bottom: 30rpx;height: 30rpx;text-align: center;color: #ff5500;"
					v-if="!manageBtn" @tap="delTheGoods(item)">
					删除
				</view>
			</view>
		</view>




		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<checkbox-group @change="onAllCheckChange">
				<checkbox value="all" :checked="isAllChecked"></checkbox>
			</checkbox-group>
			<text>全选</text>
			<view class="manage flex justify-center align-center" @tap="manageList()">
				{{manageBtn?'管理':'取消管理'}}
			</view>
			<view class="total" v-if="manageBtn">
				合计: <text class="total-price">¥{{ totalPrice }}</text>
			</view>
			<cu-btn class="settle-btn" @tap="onSettle" v-if="manageBtn">去结算</cu-btn>

			<view class="delMyCard flex justify-end align-center" :class="[toggleDelay?'animation-slide-bottom':'']"
				v-else>
				删除
			</view>


		</view>



		<view class="cu-load load-modal" v-if="loadModal">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<!-- <image src="/static/logo.png" mode="aspectFit"></image> -->
			<view class="gray-text">加载中...</view>
		</view>

	</view>
</template>
<script>
	import ColorUICounter from '@/shopping/components/Counter.vue'
	import {
		deepClone
	} from '@/utils/ruoyi.js'
	export default {
		components: {
			ColorUICounter
		},
		data() {
			return {
				// 购物车商品列表（模拟数据）
				cartList: [{
					image: "https://minio.huerai.com/peizhen/2025/10/30/1761810205347.png",
					title: '香蕉手机,最好的手机',
					skuAttr: ['12GB运行内存', '512GB储存空间'],
					price: 5799,
					totalPrice: 5799,
					skuId: 42,
					check: true,
					count: 1
				}, {
					image: "https://minio.huerai.com/peizhen/2025/10/30/1761810205347.png",
					title: '香蕉手机,最好的手机',
					skuAttr: ['16GB运行内存', '1TB储存空间'],
					price: 5799,
					totalPrice: 5799,
					skuId: 43,
					check: true,
					count: 1
				}],
				isAllChecked: false, // 全选状态
				totalPrice: 0, // 选中商品总价


				loadModal: false,

				addrForm: {},

				submitOrderForm: {},


				openWay: '', //支付方式
				isPay: true,
				note: '', //备注
				fare: '', //运费


				manageBtn: true,
				toggleDelay: false,
			}
		},
		onLoad() {
			this.getShoppingCart()
		},


		watch: {
			cartList: {
				handler(newVal) {
					console.log('newVal', newVal);
					this.updateNum(newVal)
				},
				deep: true
			},
		},


		methods: {

			updateNum(list) {
				console.log(this.cartLists);
				uni.showToast({
					title: '请稍等...',
					icon: 'loading',
					mask: true, // 关键参数
				})
				this.cartLists.forEach((item, index) => {
					if (item.count != list[index].count) {
						this.$Request.post(`/app/mallCart/countItem`, {
							skuId: item.skuId,
							num: list[index].count,
						}).then(res => {
							if (res.code == 0) {
								console.log('修改成功');
								this.getShoppingCart()
							}

						});
						setTimeout(() => {
							uni.hideLoading();
						}, 1000)
						return
					}
				})



			},





			//购物车列表
			getShoppingCart() {

				this.$Request.get(`/app/mallCart/cartList`).then(res => {
					if (res.code == 0 && res.data) {
						this.cartList = res.data.items
						this.cartLists = deepClone(res.data.items)
						this.calculateTotal() // 初始化计算总价
						let arr = this.cartList.find(item => item.check == false)
						if (arr) {
							this.isAllChecked = false
						} else {
							this.isAllChecked = true
						}
					}
				});
			},

			delTheGoods(item) {
				let that = this
				uni.showModal({
					title: '删除提示',
					content: '确认从购物车中删除该物品吗？',
					success: function(re) {
						if (re.confirm) {
							that.$Request.post(`/app/mallCart/deleteItem`, {
								skuId: item.skuId
							}).then(res => {
								if (res.code == 0) {
									uni.showToast({
										title: '删除成功',
										duration: 2000
									})
									that.getShoppingCart()
								}
							});
						} else if (re.cancel) {
							console.log('用户点击取消');
						}
					},
				})



			},

			//购物车管理
			manageList() {
				this.manageBtn = !this.manageBtn;
				this.toggleDelay = true;
				setTimeout(() => {
					this.toggleDelay = false
				}, 1000)
			},


			// 单个商品复选框变化
			onItemCheckChange(e, index) {
				const {
					value,
					check,
					skuId
				} = e
				let num


				if (check == true) {
					num = 2

				} else {
					num = 1
				}


				let data = {
					skuId: skuId,
					check: num,
				}
				uni.showToast({
					title: '请稍等...',
					icon: 'loading',
					mask: true, // 关键参数
				})
				this.$Request.post(`/app/mallCart/checkItem`, data).then(res => {
					this.getShoppingCart()
				})
				setTimeout(() => {
					uni.hideLoading();
				}, 2000)

			},

			// 全选复选框变化
			onAllCheckChange(e) {
				const isAll = e.detail.value.includes('all')
				this.cartList.forEach(item => item.check = isAll)
				this.isAllChecked = isAll
				this.$nextTick(() => {
					this.getShoppingCart()
				})

			},

			// 计算选中商品总价
			calculateTotal() {
				let total = 0
				this.cartList.forEach(item => {
					if (item.check) {
						total += item.totalPrice * 1 // 转为数字
					}
				})
				this.totalPrice = total.toFixed(2)
			},

			// 结算按钮
			onSettle() {
				// const selectedGoods = this.cartList.filter(item => item.check)
				// console.log('选中的商品：', selectedGoods)
				// 实际开发：跳转到结算页，传递选中商品数据

				let fil = this.cartList.filter(it => it.check)
				if (fil.length == 0) {
					uni.showToast({
						title: '请选择要支付的物品',
						icon: 'none',
						mask: true, // 关键参数
					})
					return
				}





				this.$Request.post(`/app/order/toTrade`).then(res => {
					if (res.code == 0 && res.data) {
						this.submitOrderForm = res.data
						uni.navigateTo({
							url: '/shopping/shoppClose/index?submitOrderForm=' + encodeURIComponent(JSON
								.stringify(this.submitOrderForm))
						})
					}
				});

			},




			//获取运费
			getYunFei() {
				this.$Request.getT('/app/ware/purchase/fare', {
					addrId: this.addrForm.id
				}).then(res => {
					console.log(res);
					if (res.code == 0 && res.data) {
						this.fare = res.data.fare
					}
				});
			},




		},

	}
</script>
<style lang="scss" scoped>
	@import "../../components/colorui/animation.css";

	.cart-page {
		background-color: #f7f7f7;
		min-height: 100vh;
		border-top: 2rpx solid #f4f4f4;

		/* 商品列表 */
		.cart-list {
			margin-top: 20rpx;

			.cu-item {
				background-color: #fff;
				margin-bottom: 20rpx;
				padding: 20rpx;

				/* 店铺信息 */
				.shop-info {
					display: flex;
					align-items: center;

					.shop-name {
						font-size: 28rpx;
						color: #333;
					}

					.arrow {
						margin-left: 10rpx;
						color: #999;
					}
				}

				/* 商品内容 */
				.goods-content {
					display: flex;
					padding: 20rpx 0;
					align-items: center;

					.goods-img {
						width: 160rpx;
						height: 160rpx;
						border-radius: 8rpx;
						margin-right: 20rpx;
					}

					.goods-info-wrap {
						flex: 1;

						.goods-title {
							width: 100%;
							font-size: 30rpx;
							color: #333;
							line-height: 44rpx;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							/* 文字超出2行省略 */
							overflow: hidden;
						}

						.goods-spec {
							font-size: 28rpx;
							color: #999;
							margin: 10rpx 0;
						}

						.tags {
							display: flex;
							flex-wrap: wrap;
							margin-bottom: 10rpx;

							.cu-tag {
								margin-right: 10rpx;
								margin-bottom: 10rpx;
								font-size: 24rpx;
							}
						}

						.price-section {
							display: flex;
							align-items: center;
							// justify-content: space-between;

							.current-price {
								color: #ff6700;
								font-size: 32rpx;
								font-weight: bold;
							}



							.discount {
								font-size: 28rpx;
								color: #ff6700;
								margin-left: 30rpx;
							}

							.detail {
								font-size: 28rpx;
								color: #666;
							}
						}

						.coupon-desc {
							font-size: 28rpx;
							color: #ff6700;
						}
					}
				}
			}
		}

		/* 底部操作栏 */
		.bottom-bar {
			width: 100%;
			position: fixed;
			bottom: 0;
			left: 0;
			height: 140rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			padding: 20rpx 20rpx 20rpx 20rpx;
			border-top: 1px solid #eee;
			justify-content: space-between;

			.manage {
				margin: 0 50rpx;
				height: 100%;

			}

			.total {
				flex: 1;
				text-align: right;

				.total-price {
					color: #ff6700;
					font-size: 32rpx;
					font-weight: bold;
				}
			}

			.settle-btn {
				width: 200rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				border-radius: 40rpx;
				background-color: #ff6700;
				color: #fff;
				font-size: 32rpx;
			}

			.delMyCard {
				flex: 1;
				padding-right: 40rpx;
				animationDelay: 0.8s;
				color: #ff5500;
			}

		}
	}

	.box {
		width: 100%;
		height: 100vh;
		background: rgba(0, 0, 0, 0.7);
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		z-index: 9999;
	}

	.bottbox {
		position: fixed;
		bottom: 0upx;
		left: 0;
		right: 0;
		z-index: 9999;
		background: #ffffff;
	}




	image[class*="gif-"] {
		border-radius: 6upx;
		display: block;
	}
</style>